<?php
/**
 * 缓存类
 * 采用文件缓存方式
 */
class cache
{

	private static $_dir = null; //缓存目录
	/**
	 * 设置缓存
	 * @method set
	 * @param  [type]  $name   [description]
	 * @param  [type]  $value  [description]
	 * @param  mixed $expire [有效时间]
	 * @author NewFuture
	 */
	public static function set($name, $value, $expire = false)
	{
		$filename = self::getPath($name);
		$cache    = array(
			'e' => $expire ? (time() + $expire) : 0,
			'c' => $value,
		);
		//序列化写入文件
		return file_put_contents($filename, serialize($cache));
	}

	/**
	 * 读取缓存数据
	 * @method get
	 * @param  [type] $name [description]
	 * @return [type]       [description]
	 * @author NewFuture
	 */
	public static function get($name)
	{
		$filename = self::getPath($name);
		if (!is_file($filename))
		{
			//文件不存在
			return null;
		}

		$content = file_get_contents($filename);
		$cache   = unserialize($content);
		if ($cache['e'] && $_SERVER['REQUEST_TIME'] > $cache['e'])
		{
			//文件过期
			@unlink($filename);
			return null;
		}
		else
		{
			return $cache['c'];
		}
	}

	/**
	 * 删除缓存数据
	 * @method del
	 * @param  [type] $name [description]
	 * @return [bool]       [description]
	 * @author NewFuture
	 */
	public static function del($name)
	{
		$filename = self::getPath($name);
		return is_file($filename) ? unlink($filename) : false;
	}

	/**
	 * 删除全部缓存数据
	 * @method clear
	 * @return [type] [description]
	 * @author NewFuture
	 */
	public static function clear()
	{
		self::getPath('');
		$dir = self::$_dir;
		/*获取全部文件*/
		$files = scandir($dir);
		unset($files[0]);
		unset($files[1]);
		foreach ($files as $f)
		{
			@unlink($dir . $f);
		}
	}

	/**
	 * 刷新数据，删除缓存数据
	 * @method refresh
	 * @return [type]  [description]
	 * @author NewFuture
	 */
	public static function refresh()
	{
		self::getPath('');
		/*读取文件*/
		$dir   = self::$_dir;
		$files = scandir($dir);
		unset($files[0]);// 销毁第一个点
		unset($files[1]);//销毁第二个两点
		$current_time = time();
		foreach ($files as $f)
		{
			$content = file_get_contents($dir . $f);
			$cache   = @unserialize($content);
			if ($cache && $cache['e'] && $current_time >= $cache['e'])
			{
				@unlink($dir . $f); //文件过期
			}
		}
	}

	/**
	 * 获取文件存储路径，完整文件名
	 * @method getPath
	 * @param  [type]  $name [description]
	 * @return [type]        [description]
	 * @author NewFuture
	 */
	protected static function getPath($name)
	{
		$dir = self::$_dir;
		if ($dir === null)
		{
			//从配置中读取目录
			$dir        = Yaf_Application::app()->getConfig()->cache->dir;
			self::$_dir = $dir;
			if (!is_dir($dir))
			{
				mkdir($dir); //目录不存在则创建
			}
		}
		return $dir . $name . '.php';
	}
}